package com.zzyl.intercept;


import cn.hutool.core.map.MapUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInterceptor implements     HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断是否是映射到方法上 比如跨域请求，静态请求 不需要身份校验
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //来到这里的请求都是进入controller中
//        authorization: eyJhbGciOiJIUzI1Ni
        String token = request.getHeader("authorization");
        log.info("用户拦截器 token:{}",token);

        if (token == null || token.length()==0){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //开始解析toekn

        Claims claims = JwtUtil.parseJWT("itheima", token);

        Long userid = MapUtil.get(claims, "userid", Long.class);
        log.info("用户拦截器 userid:{}",userid);
        if (userid == null){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        // 至此 校验完毕，可以放行
        System.out.println("拦截器  当前线程id："+Thread.currentThread().getId());

        UserThreadLocal.set(userid);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //每个请求，都会开启一个线程，在请求结束后，会调用这个方法，所以这里需要清理一下
        UserThreadLocal.remove();
    }
}
